﻿CREATE PROCEDURE [dbo].[sp_Get_Territory]
(
	@MdNumber varchar(10),
	@PeroidMonth int,
	@PeroidYear int
)
AS
	IF @MdNumber IS NULL
	BEGIN
		select MdNumber, Territory from dbo.ZipInfo 
		WHERE Territory is not null
		group by MdNumber, Territory order by Territory
	END
	ELSE
	BEGIN
		select zi.MdNumber, zi.Territory from dbo.ZipInfo zi
		inner join dbo.OrderZip oz on zi.ZipID = oz.ZipID
		inner join dbo.Orders o on o.OrderID = oz.OrderID
		WHERE zi.Territory is not null and o.AccountID = @MdNumber 
		and o.PeroidMonth = @PeroidMonth and o.PeroidYear = @PeroidYear
		group by zi.MdNumber, zi.Territory order by zi.Territory
	END